<template>
  <view class='detail2-container' id="container" v-if="inited">
    <PracticeNavbar id="navbar" v-if="model==='lianxi'" :title="title" @changeMode="changeMode"
                    :storeId="storeId"
                    @settingClick="onSettingClick"></PracticeNavbar>
    <ExamNavbar id="navbar" v-else ref="examNavbar" :storeId="storeId" :kemu="kemu" @pause="pauseExam" @settingClick="onSettingClick"></ExamNavbar>
    <TiyanDialog :nav="true"></TiyanDialog>
    <SwiperDetail style="position: relative;flex: 1"
                  ref="swiperDetail"
                  :isManfen="isManfen"
                  :storeId="storeId"
                  :kemu="kemu"
                  :mode="mode"
                  :type="type"></SwiperDetail>
    <!-- 答题卡 -->
    <AnswerPanel ref="answerPanelPopup" :type="type" :storeId="storeId"></AnswerPanel>
    <ExamAnswerInfo v-if="model==='kaoshi'" :storeId="storeId"></ExamAnswerInfo>
    <Footer id="footer" ref="footer" @showAnswerPanel="showAnswerPanel" :type="type" :storeId="storeId"></Footer>
    <ClearAnswerDialog :type="type" :storeId="storeId"></ClearAnswerDialog>
    <PauseExamDialog ref="pauseExamPopup" v-if="model==='kaoshi'" :storeId="storeId"></PauseExamDialog>
    <SubmitExamDialog ref="submitExamPopup" v-if="model==='kaoshi'" :storeId="storeId" :correctNumMin="correctNumMin"
                      :errorNumMax="errorNumMax"></SubmitExamDialog>
    <RemoveErrorBookDialog v-if="type ==='wrong'" :storeId="storeId"></RemoveErrorBookDialog>
    <AddMineMinProgram></AddMineMinProgram>
    <WrongAnswerDialog ref="WrongAnswerDialog"></WrongAnswerDialog>
    <WXPageBackIntercept ref="mpBack" @back="onMpBack" :storeId="storeId"></WXPageBackIntercept>
    <SettingDialog ref="SettingDialog" :storeId="storeId"></SettingDialog>
    <ReportDialog ref="ReportDialog"></ReportDialog>
    <FreeOpenAnswerToast></FreeOpenAnswerToast>
  </view>
</template>

<script>
import {mapGetters, mapActions} from 'vuex'
import PracticeNavbar from "@/pages/detail/PracticeNavbar";
import ExamNavbar from "@/pages/detail/ExamNavbar";
import SettingDialog from "@/pages/detail/SettingDialog";
import SwiperDetail from "@/pages/detail/SwiperDetail";
import Footer from "@/pages/detail/Footer";
import AnswerPanel from "@/pages/detail/AnswerPanel";
import ClearAnswerDialog from "@/pages/detail/ClearAnswerDialog";
import RemoveErrorBookDialog from "@/pages/detail/RemoveErrorBookDialog";
import ExamAnswerInfo from "@/pages/detail/ExamAnswerInfo";
import PauseExamDialog from "@/pages/detail/PauseExamDialog";
import SubmitExamDialog from "@/pages/detail/SubmitExamDialog";
import questionCache from "@/libs/questionCache";
import WXPageBackIntercept from "@/components/WXPageBackIntercept.vue";
import audioHelper from "@/libs/audioHelper";
import shareUtils from "@/libs/shareUtils";
import utils from "@/libs/utils";
import AddMineMinProgram from "@/pages/home/AddMineMinProgram.vue";
import WrongAnswerDialog from "@/components/WrongAnswerDialog.vue";
import ReportDialog from "@/components/ReportDialog.vue";
import FreeOpenAnswerToast from "./FreeOpenAnswerToast.vue";
import TiyanDialog from "@/components/TiyanDialog.vue";

export default {
  name: 'detail',
  components: {
    TiyanDialog,
    FreeOpenAnswerToast,
    ReportDialog,
    WrongAnswerDialog,
    WXPageBackIntercept,
    Footer,
    PracticeNavbar,
    SwiperDetail,
    AnswerPanel,
    ClearAnswerDialog,
    RemoveErrorBookDialog,
    ExamNavbar,
    SettingDialog,
    ExamAnswerInfo,
    PauseExamDialog,
    AddMineMinProgram,
    SubmitExamDialog
  },
  data() {
    return {
      mode: 'answer',
      title: '',
      list: [],
      type: '',
      kemu: '',
      storeId: null,
      inited: false,
      initIndex: 0,
      currentIndex: 0,
      detailHeight: 0,
      isManfen: false,
    }
  },
  computed: {
    ...mapGetters(['topBar', 'settings', 'mine', 'systemInfo']),
    // 最少对多少题目
    correctNumMin() {
      if (this.kemu === '1') {
        return parseInt(this.settings.kemu1PassScore)
      }
      return parseInt(this.settings.kemu4PassScore)
    },
    //最多允许错
    errorNumMax() {
      if (this.kemu === '1') {
        return parseInt(this.settings.kemu1NoPassScore)
      }
      return parseInt(this.settings.kemu4NoPassScore)
    },
    //做题模式 1普通答题模式 2考试模式
    model() {
      if (this.type === 'moni') {
        return 'kaoshi'
      } else {
        return 'lianxi'
      }
    },
  },
  onShareAppMessage(args) {
    const data = shareUtils.getPageShare()
    console.log(this.list, this.currentIndex)
    if (this.list[this.currentIndex]) {
      data.path = '/pages/detail/detail?type=share&title=分享&questionId=' + this.list[this.currentIndex].id
      data.title = '这道题该怎么做？'
      delete data.imageUrl
    }

    return data
  },
  onLoad(query) {
    this._query = query
    const {isManfen = false} = this._query
    this.isManfen = isManfen
    this.init(this._query).catch(e => {
      console.log(e)
    })
  },

  /**
   * 目前已知微信小程序不兼容
   * https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle
   * @param args
   * @returns {boolean}
   */
  onBackPress(args) {
    if (this.$refs.WrongAnswerDialog && this.$refs.WrongAnswerDialog.isShowing()) {
      if (this.$refs.WrongAnswerDialog.isVIPQuanyiDialogShowing()) {
        this.$refs.WrongAnswerDialog.closeVIPQuanyiDialog()
      } else {
        this.$refs.WrongAnswerDialog.quit()
      }
      return true
    }
    return this._backPress(args)
  },
  destroyed() {
    console.log('detail page destroyed')
    questionCache.destroyStore(this.storeId)
    audioHelper.destroy()
  },
  mounted() {
  },
  methods: {
    ...mapActions('question', ['questionList']),
    async init({type = 'moni', list, kws, kemu, today, title, questionId = null}) {
      uni.showLoading({
        title: '加载题库中',
        mask: true
      })
      this._starTime = parseInt(new Date().getTime() / 1000);
      console.error('####### detail title：', title, 'type：', type, 'kemu：', kemu, 'list：', list ? list.length : 0, '###########')
      this.type = type
      this.title = title
      this.kemu = kemu
      audioHelper.create()
      let haoStart = Date.now()

      // this.detailHeight = this.systemInfo.screenHeight - this.topBar.height - this.topBar.navbarHeight - this.topBar.navbarHeight - 6
      // console.log(this.systemInfo, this.detailHeight)
      // console.log(this.systemInfo.screenHeight, this.topBar.height, this.topBar.navbarHeight, this.topBar.navbarHeight)

      if (list && list.length) {
        list = JSON.parse(decodeURIComponent(list))
        if (list.length) {
          if (!questionId) {
            questionId = list[0].id
          }
        }
        await utils.sleep(300)
      } else if (type === 'share') {
        list = [{id: questionId}]
      } else {
        const res = await this.questionList({type, kemu, kws, today})
        list = res.list
        if (!questionId) {
          // list = res.data.data.list.splice(0, 10)
          questionId = res.lastQuestionId
        }
      }
      uni.setNavigationBarTitle({
        title
      })
      let index = 0

      if (questionId) {
        index = list.findIndex(item => item.id == questionId)
      }
      this.initIndex = index
      this.currentIndex = index

      this.storeId = questionCache.createStore()
      const questionStore = questionCache.getStore(this.storeId)

      questionStore.setQuestions(list)
      questionStore.subscribe('changeIndex', (index) => {
        console.log('current index', index)
        this.currentIndex = index
      })
      const wait = 1000 - (Date.now() - haoStart)

      console.log('wait', wait)
      setTimeout(() => {
        questionStore.initList(index, list)
      }, wait > 0 ? wait : 0)
      this.list = list

      /**
       * 维护本地缓存数据
       * @type {{}}
       */
      questionStore.subscribe('exitExam', () => {
        this.forceExitExam()
      })

      questionStore.subscribe('navigateToExamEnd', () => {
        this.navigateToExamEnd()
      })
      questionStore.subscribe('submitExam', () => {
        const finishNum = this._errorNumNow + this._correctNumNow
        const max = list.length
        if (finishNum === max) {
          this.navigateToExamEnd()
        } else {
          const timeLeft = this.$refs.examNavbar.pause()
          this.$refs.submitExamPopup.open(finishNum, max, this._correctNumNow, this._errorNumNow, timeLeft)
        }
      })

      questionStore.subscribe('resumeExam', () => {
        this.resumeExam()
      })
      questionStore.subscribe('pauseExam', () => {
        if (this.$refs.examNavbar) {
          if (this.$refs.examNavbar.isPaused()) {
            return true
          }

          const timeLeft = this.$refs.examNavbar.pause()
          this.pauseExam(timeLeft, 'pause')
        }
      })

      questionStore.subscribe('removeQuestion', ({index}) => {
        this.list.map(item => console.log(item.id))
        this.list.splice(index, 1)
        questionStore.setQuestions(this.list)
        if (this.list.length === index) {
          index = this.list.length - 1
        }
        questionStore.initList(index, this.list)
        this.list.map(item => console.log(item.id))
      })

      this._errorNumNow = 0
      this._correctNumNow = 0
      questionStore.subscribe('unlockVIP', ({question, from}) => {
        // console.log(' question.kemu question.kemu question.kemu question.kemu', question.kemu)
        if (from === 'error') {
          this.$refs.WrongAnswerDialog.open('回答错误', question.kemu, this.isManfen)
        } else {
          this.$refs.WrongAnswerDialog.open('解锁试题详解', question.kemu, this.isManfen)
        }
      })
      questionStore.subscribe('answer', ({id, index, result, status, question}) => {
        if (status === -1) {
          this._errorNumNow++
        } else {
          this._correctNumNow++
        }

        if (this._correctNumNow + this._errorNumNow === 10) {
          this.$refs.ReportDialog.open()
        }

        if (this.model === 'kaoshi') {
          // 刚失败
          if (this._errorNumNow === this.errorNumMax + 1) {
            questionStore.publish('submitExam')
          }
        }
      })

      setTimeout(() => {
        uni.hideLoading()
        this.inited = true
        this.$nextTick(() => {
          this.$refs.examNavbar && this.$refs.examNavbar.resume()
        })
      }, 1000)
    },

    onMpBack(args) {
      const intercepted = this._backPress(args)
      if (intercepted) {
        this.$refs.mpBack.setData(true)
      } else {
        uni.navigateBack()
      }
    },

    _backPress({from}) {
      console.log(from)
      let res

      if (this.model === 'lianxi') {
        res = this.navigateToDetailEnd()
        if (res) {
          return true
        }
      } else {
        // 小于1000毫秒是强制退出
        if (this._forceExitExamTime && Date.now() - this._forceExitExamTime < 1000) {
          return false
        }

        if (this.$refs.examNavbar.isPaused()) {
          return true
        }

        const timeLeft = this.$refs.examNavbar.pause()
        this.pauseExam(timeLeft, 'exit')
        return true
      }
    },
    forceExitExam() {
      this._forceExitExamTime = Date.now()
      uni.navigateBack()
    },
    pauseExam(timeLeft, mode) {
      this.$refs.pauseExamPopup.open(this._errorNumNow + this._correctNumNow, this.list.length, timeLeft, mode)
    },
    resumeExam() {
      this.$refs.submitExamPopup.close()
      this.$refs.pauseExamPopup.close()
      this.$refs.examNavbar.resume()
    },
    changeMode(mode) {
      this.mode = mode;
    },
    onSettingClick() {
      this.$refs.SettingDialog.open()
    },
    showAnswerPanel() {
      this.$refs.answerPanelPopup.open()
    },

    // 去考试结果页
    navigateToExamEnd() {
      if (this.model !== 'kaoshi') {
        return
      }
      const now = parseInt(new Date().getTime() / 1000)
      const time = now - this._starTime
      const problemNum = this._errorNumNow + this._correctNumNow
      uni.redirectTo({
        url: '/pages/exam_score/exam_score?type=' + this.type +
          '&time=' + time +
          '&kemu=' + this.kemu +
          '&problemNum=' + problemNum +
          '&errorNum=' + this._errorNumNow
      })
    },

    // 去本次练题情况
    navigateToDetailEnd() {
      if (this.model !== 'lianxi') {
        return
      }

      const now = parseInt(new Date().getTime() / 1000)
      const time = now - this._starTime
      const problemNum = this._errorNumNow + this._correctNumNow
      if (this.type !== 'wrong' && this.type !== 'search' && this.type !== 'collect') {
        if (problemNum) {
          uni.redirectTo({
            url: '/pages/detail_end/detail_end?type=' + this.type +
              '&time=' + time +
              '&kemu=' + this.kemu +
              '&problemNum=' + problemNum +
              '&errorNum=' + this._errorNumNow
          })
          return true;
        }
      }
    }
  }
}
</script>

<style lang='scss'>
page {
  height: 100%;
}

.detail2-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}
</style>
